package classes {
	import UIFree.ObjectEvent;
	
	import UIUtils.Exif.ExifHeader;
	import UIUtils.JPGEncoder;
	import UIUtils.uif_MLPEncoder;
	import UIUtils.uif_util;
	import UIUtils.uif_utilBitmap;
	
	import flash.display.BitmapData;
	import flash.display.DisplayObjectContainer;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Point;
	import flash.utils.ByteArray;

	public class c_imageTypes {
		public static const JPG: String = 'jpg';
		public static const MLP: String = 'mlp';
		public static const PNG: String = 'png';
		
		public static const MLPDATACOMPLETE: String = 'MLPDATACOMPLETE';
		
		public static function encodeFromMLP(elem: DisplayObjectContainer): ByteArray {
			return uif_MLPEncoder.encode(elem, [
				{
					type: uif_MLPEncoder.TYPEBLOCKURL,
					data: 'http://188.127.227.87'
				}
			]);
		}
		
		public static function encodeFromJPG(bmd: BitmapData, exifHeader: Object, resize: Point=null): ByteArray {
			var je: JPGEncoder = new JPGEncoder(80);
			return je.encode(bmd, new ExifHeader(exifHeader));
		}
		
		public static function baToLoader(bytes: ByteArray, afterProc: Function): void {
			function doCompleteJPG(e: Event): void {
				afterProc(e.target.loader);
				e.target.loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, doCompleteJPG);
			}
			var loader: Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, doCompleteJPG);
			loader.loadBytes(bytes);
		}
		
		public static function baToBmd(bytes: ByteArray, afterProc: Function): void {
			baToLoader(bytes, function(loader: Loader): void {
				var bmd: BitmapData = uif_utilBitmap.copyBitmapData(loader);
				loader.unload();
				afterProc(bmd);
			}) 
		}
		
		public static function loadBytes(workspace: EventDispatcher, bytes: ByteArray, fileType: String): void {
			var ext: String = fileType.toLowerCase();
			if (ext.substr(0, 1) == '.') ext = ext.substr(1);
			if ((ext == c_imageTypes.JPG) || (ext == c_imageTypes.PNG)) {
				baToLoader(bytes, function(a_loader: Loader): void {
					workspace.dispatchEvent(new ObjectEvent(c_events.IMAGELOADCOMPLETE, {
						image	: a_loader,
						params	: null
					}));
				})
			} else if (ext == c_imageTypes.MLP) {
				uif_MLPEncoder.decode(bytes, function(bmps: Array): void {
					workspace.dispatchEvent(new ObjectEvent(MLPDATACOMPLETE, bmps));
				});
			}
		}
	}
}